import { getGovernment } from '@/api/agriculture.ts';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

export const useGovernmentStore = defineStore('GovernmentStore', () => {
  const LinkSets = ref<[]>([]);
  const loading = ref<boolean>(false);
  const linkPage = ref({
    currentPage: 1,
    total: 0,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: Array.from({ length: 200 }, (_, index) => index + 1),
  });

  const updateGovernmentLink = async () => {
    loading.value = true;
    const req = {
      pageNo: linkPage.value.currentPage,
      pageSize: linkPage.value.pageSize,
    };

    const res = await getGovernment(req);
    const { data, meta } = res;
    LinkSets.value = data.map((item: any) => ({
      url: item.attributes.url,
      description: item.attributes.description,
    }));
    linkPage.value.total = meta.pagination.total;
    loading.value = false;
  };

  // 设置分页信息
  const setLinkSetsPage = (page?: number) => {
    if (page) linkPage.value.currentPage = page;
  };

  const getLinkSets = computed(() => {
    return LinkSets.value;
  });

  const getLinkPage = computed(() => {
    return linkPage.value;
  });

  const pagination = computed(() => ({
    current: linkPage.value.currentPage,
    total: linkPage.value.total,
    pageSize: linkPage.value.pageSize,
    onChange: (page: number) => {
      setLinkSetsPage(page);
      updateGovernmentLink().then();
    },
  }));

  const getLinkLoading = computed(() => {
    return loading.value;
  });

  return {
    LinkSets,
    updateGovernmentLink,
    getLinkSets,
    setLinkSetsPage,
    getLinkPage,
    pagination,
    getLinkLoading,
  };
});
